package com.yy.module.service;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.yy.base.common.service.BaseService;
import com.yy.module.entity.Field;
import com.yy.module.entity.Table;

@Service("tableService")
@SuppressWarnings("unchecked")
public class TableService extends BaseService {
	/**
	 * 查询表信息
	 */
	public List getFieldList(Field field, String tableName){
		StringBuilder sql = new StringBuilder();
		sql.append("from Field where isActive = 'Y'");
		List paramList = new ArrayList();
		
		if (field.getName() != null && !"".equals(field.getName())) {
			sql.append(" and (name like ? or text like ?)");
			paramList.add("%" + field.getName() + "%");
			paramList.add("%" + field.getName() + "%");
		}
		if (field.getTableId() != null) {
			sql.append(" and tableId = ?");
			paramList.add(field.getTableId());
		}
		if (tableName != null && !"".equals(tableName)) {
			sql.append(" and tableId in (select t.id from Table t where t.name = ?)");
			paramList.add(tableName);
		}
		return dao.find(sql.toString(), paramList.toArray());
	}
	/**
	 * 查询表信息
	 */
	public List getTableList(Table table){
		return dao.find("from Table where isActive = 'Y' order by created");
	}
	/**
	 * 查询表信息
	 */
	public List getTableJoinList(String tableName) {
		return dao.find("from TableJoin where tableName1 = ?", tableName);
	}
	/**
	 * 查询表信息
	 */
	public List getTableType(){
		return dao.find("from Table t where t.isActive = 'Y' and t.isParent = 1 order by parentId");
	}
	
	/**
	 * 查询字段信息 
	 */
	public Field getFieldInfoById(String id) {
		return dao.get(Field.class, id);
	}
	/**
	 * 查询字段信息
	 */
	public Field getFieldInfoById(String fieldName, String tableId) {
		return (Field)dao.findUnique("from Field where name = ? and tableId=?", fieldName, tableId);
	}
	/**
	 * 查询表信息 
	 */
	public Table getTableInfoById(String id) {
		return dao.get(Table.class, id);
	}
	/**
	 * 根据字段查询之前已有字段中的名称
	 */
	public Field getFieldByName(String name) {
		List<Field> list = dao.find("from Field where isActive = 'Y' and name = ? order by updated desc", name);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	public List getFields(String table) {
		return dao.getFields(table);
	}
}